package com.mky.mkcompany.controller;


import com.alibaba.fastjson.JSONObject;
import com.mky.mkcompany.dic.FileCheckDic;
import com.mky.mkcompany.service.TopicManageService;
import com.mky.mkcompany.tool.FileDownloadUtil;
import com.mky.mkcompany.tool.UploadFileUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.nio.file.Paths;
import java.util.Date;

@RestController
public class UploadFileController {
	private final Logger LOGGER = LoggerFactory.getLogger(getClass());
	public static final String filePath = "uploadFile/mkcompany";
	@Autowired
	private ResourceLoader resourceLoader;

	@Autowired
	private TopicManageService topicManageService;

	/**
	 * spring boot-获取图片前端显示
     */
	@RequestMapping(method = RequestMethod.GET, value = "/v0.1/uploadFile/path/{filename:.+}")
	//@Authorization
	@ResponseBody
	public ResponseEntity<?> getFile(@PathVariable String filename) {

		try {
			return ResponseEntity.ok(resourceLoader.getResource("file:" + Paths.get(filePath, filename).toString()));
		} catch (Exception e) {
			return ResponseEntity.notFound().build();
		}
	}

	/**
	 * spring boot 上传文件
     */
	@RequestMapping(method = RequestMethod.POST, value = "/v0.1/uploadFile")
	//@Authorization
	public Object handleFileUpload(@RequestParam("file") MultipartFile file,
								   RedirectAttributes redirectAttributes, HttpServletRequest request) {
		JSONObject res = new JSONObject();
		LOGGER.info("上传文件开始file="+file);
		res= UploadFileUtil.uploadFile(file,filePath, FileCheckDic.DWG_FILE_CHECK);
		res.put("success",true);
		res.put("status",200);
		return res;
	}


	/**
	 * spring boot 下载文件
	 */
	@RequestMapping(method = RequestMethod.GET, value = "/v0.1/fileDownload/{filename:.+}")
	//@Authorization
	public void downloadFile(@PathVariable String filename, HttpServletRequest request
			, HttpServletResponse response) {
		try {
			String path= Paths.get(filePath, filename).toString();
			Resource resource=resourceLoader.getResource("file:" +path);
			File file=resource.getFile();
			FileDownloadUtil.fileDownload(request,response,file,file.getName());
		} catch (Exception e) {
		}
	}

	/**
	 * spring boot 下载文件
	 */
	@RequestMapping(method = RequestMethod.GET, value = "/v0.1/fileView/{filename:.+}")
	//@Authorization
	public void viewFile(@PathVariable String filename, HttpServletRequest request
			, HttpServletResponse response) {
		try {
			String path= Paths.get(filePath, filename).toString();
			Resource resource=resourceLoader.getResource("file:" +path);
			File file=resource.getFile();
			FileInputStream inputStream = null;
			try {
				inputStream = new FileInputStream(file);
				byte[] data = new byte[(int) file.length()];
				int length = inputStream.read(data);
				inputStream.close();
				//setContentType("text/plain; charset=utf-8"); 文本
				//response.setContentType("image/png;charset=utf-8");
				OutputStream stream = response.getOutputStream();
				stream.write(data);
				stream.flush();
				stream.close();
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
		} catch (Exception e) {
		}
	}

	@RequestMapping(value = "/test1/{filename:.+}", method = RequestMethod.GET)
	public ResponseEntity<FileSystemResource> exportXls(@PathVariable String filename, HttpServletRequest request
			, HttpServletResponse response) {
		String path= Paths.get(filePath, filename).toString();
		Resource resource=resourceLoader.getResource("file:" +path);
		File file=null;
		try {
			file=resource.getFile();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return export(file);
	}

	public ResponseEntity<FileSystemResource> export(File file) {
		if (file == null) {
			return null;
		}
		HttpHeaders headers = new HttpHeaders();
		headers.add("Cache-Control", "no-cache, no-store, must-revalidate");
		headers.add("Content-Disposition", "attachment; filename=" + System.currentTimeMillis() + ".xls");
		headers.add("Pragma", "no-cache");
		headers.add("Expires", "0");
		headers.add("Last-Modified", new Date().toString());
		headers.add("ETag", String.valueOf(System.currentTimeMillis()));

		return ResponseEntity
				.ok()
				.headers(headers)
				.contentLength(file.length())
				//.contentType(MediaType.parseMediaType("application/octet-stream"))
				.body(new FileSystemResource(file));
	}


}
